import os
from collections import OrderedDict

from goods.models import SKU, Goods
from celery_tasks.main import app
from django.conf import settings
from django.template import loader

from utils.goods import get_categories

# 静态化列表页
@app.task(bind=True, name='generate_list_category_html')
def generate_list_category_html(self):
    # 获取分类
    categories = get_categories()

    # 拼接数据
    context = {
        'categories': categories,
    }

    # 获取模板
    template = loader.get_template('list.html')
    html_data = template.render(context)

    # 将文件写入

    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'list.html')

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_data)


# 静态化商品详情页
@app.task(name='generate_static_sku_detail_html')
def generate_static_sku_detail_html(sku_id):
    # 获取分类数据
    categories = get_categories()
    sku = SKU.objects.get(id=sku_id)
    sku.images = sku.skuimage_set.all()

    # 获取面包屑数据
    goods = sku.goods
    goods.channel = goods.category1.goodschannel_set.all()[0]
    # 获取商品规格项ids
    sku_key = []
    sku_specs = sku.skuspecification_set.order_by('spec_id')
    for sku_spec in sku_specs:
        sku_key.append(sku_spec.option.id)

    # 构建商品规格
    # 获取所有商品
    skus = goods.sku_set.all()

    # 构建不同规格参数的sku字典
    spec_sku_map = {}
    for s in skus:
        speces = sku.skuspecification_set.order_by('spec_id')
        # 记录规格参数id
        key = []
        for spec in speces:
            key.append(spec.option.id)

        # 添加数据
        spec_sku_map[tuple(key)] = s.id

    specs = goods.goodsspecification_set.order_by('id')
    # 若当前sku的规格信息不完整,则不再继续
    if len(sku_key) < len(specs):
        return
    # 针对商品数进行遍历
    for index, spec in enumerate(specs):
        # 复制当前sku的规格
        key = sku_key[:]
        options = spec.specificationoption_set.all()
        for option in options:
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))

        spec.options = options

        # 组织上下文
        context = {
            'categories': categories,
            'goods': goods,
            'specs': specs,
            'sku': sku
        }
        template = loader.get_template('detail.html')
        html_text = template.render(context)
        file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR,
                            'goods/' + str(sku_id) + '.html')
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(html_text)


